package com.example.drive.net.callback

import android.util.Log
import com.google.gson.Gson
import okhttp3.Response
import java.lang.reflect.ParameterizedType

/**
 * 返回实体类
 */
abstract class EntityCallback<T> : NetworkCallback<T> {
    companion object {
        private const val TAG = "EntityCallback"
    }

    private val gson: Gson by lazy {
        Gson()
    }

    // 得到泛型T的Class
    private val classOfT: Class<T>? by lazy {
        kotlin.runCatching {
            val pt = javaClass.genericSuperclass as? ParameterizedType
            pt?.actualTypeArguments?.get(0) as? Class<T>
        }.getOrElse {
            Log.e(TAG, "get classOfT error:$it")
            null
        }
    }

    override fun parseNetworkResponse(response: Response): T? {
        return kotlin.runCatching {
            val json = response.body.string()
            gson.fromJson(json, classOfT)
        }.getOrElse {
            Log.e(TAG, "parseNetworkResponse error:$it")
            null
        }
    }
}